import { useLocalStorage } from '@vueuse/core';
import { storeToRefs } from 'pinia';
import { useToast } from 'primevue/usetoast';

export function useShopList(store) {
  const toast = useToast();
  const { addToCartList } = store;
  const { cartList } = storeToRefs(store);

  const cartListStore = useLocalStorage('cart-list', []);

  function onClick(product) {
    // if the product is already in the cart, do nothing
    if (cartList.value.some((item) => Number(item.id) === Number(product.id))) {
      // Toast error

      toast.add({
        severity: 'error',
        summary: 'The product is already in the cart',
        life: 3000,
      });
      return;
    }

    addToCartList(product);
    cartListStore.value = [...cartListStore.value, product];
    toast.add({
      severity: 'success',
      summary: 'Added to cart',
      life: 1000,
    });
  }

  return { onClick };
}
